package com.lenovo.leos.letools.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lenovo.leos.filebrowser.netdisk.Log;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class FileDownloadService {

	private DBOpenHelper openHelper;

	/** 表中字段isover对应的值 **/
	public static final int loadover_no = 0;
	public static final int loadover_yes = 1;
	
	/** 表中字段isloading对应的值 **/
	public static final int isloading_no = 0;
	public static final int isloading_yes = 1;

	public FileDownloadService(Context context) {
		openHelper = new DBOpenHelper(context);
	}

	/**
	 * 更改下载文件的状态
	 * 
	 * @param path
	 *            isover_no 未完成；isover_yes已完成
	 */
	public void updateIsOver(String path, int loadoverVal) {
		String sql = "update filedownlog set loadover=? where downpath=?";
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.beginTransaction();
		try {
			db.execSQL(sql, new Object[] {loadoverVal,path});
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
		}
		db.close();
	}
	
	public boolean isDownLoading(String strwholepath)throws Exception{
		String sql = "select isloading from filedownlog where fileWholePath=?";
		SQLiteDatabase db = openHelper.getWritableDatabase();
		int data = 0;
		boolean flag = false;
		Cursor cursor = db.rawQuery(sql,new String[] { strwholepath });
		while (cursor.moveToNext()) {
			data = cursor.getInt(0);
			if(data == 1){
				flag = true;
			}
		}
		db.close();
		if(flag == true){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 更改下载文件的状态
	 * 
	 * @param path
	 *            isloading_no 未下载；isloading_yes正在下载
	 */
	public void updateIsLoading(String path, int isloadingVal) {
		String sql = "update filedownlog set isloading =? where downpath=?";
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.beginTransaction();
		try {
			db.execSQL(sql, new Object[] {isloadingVal,path});
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
		}
		db.close();
	}

	/**
	 * 获取每条线程已经下载的文件长度
	 * 
	 * @param path
	 * @return
	 */
	public int getData(String path) {
		int data = 0;
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(
				"select downlength from filedownlog where downpath=?",
				new String[] { path });
		while (cursor.moveToNext()) {
			data = cursor.getInt(0);
		}
		cursor.close();
		db.close();
		return data;
	}
	
	/**
	 * 获取指定文件id的所有信息
	 * @param path
	 * @return
	 */
	public FileDownloadEntity getFileDownloadEntity(String path){
		FileDownloadEntity entity=null;
		String sql = "select * from filedownlog where downpath=?";
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(sql, new String[]{path});
		if(cursor.moveToFirst()){
			int id = cursor.getInt(cursor.getColumnIndex("id"));
			String downpath = cursor.getString(cursor
					.getColumnIndex("downpath"));
			int downlength = cursor.getInt(cursor.getColumnIndex("downlength"));
			int filelen = cursor.getInt(cursor.getColumnIndex("filelen"));
			int loadover = cursor.getInt(cursor.getColumnIndex("loadover"));
			int isloading = cursor.getInt(cursor.getColumnIndex("isloading"));
			String fileWholePath = cursor.getString(cursor
					.getColumnIndex("fileWholePath"));
			String topDirid = cursor.getString(cursor
					.getColumnIndex("topDirid"));
			String topDiridWholePath = cursor.getString(cursor
					.getColumnIndex("topDiridWholePath"));
			entity = new FileDownloadEntity(id, downpath, downlength, filelen,loadover,
					isloading,fileWholePath,topDirid,topDiridWholePath);
		}
		cursor.close();
		db.close();
		return entity;
	}
	
	//add by gaoge 2011-04-21
	/**
	 * 获取指定文件path的所有信息
	 * @param path
	 * @return
	 */
	public FileDownloadEntity getFileDownloadEntityByRealPath(String filePath){
		FileDownloadEntity entity=null;
		String sql = "select * from filedownlog where fileWholePath=?";
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(sql, new String[]{filePath});
		if(cursor.moveToFirst()){
			int id = cursor.getInt(cursor.getColumnIndex("id"));
			String downpath = cursor.getString(cursor
					.getColumnIndex("downpath"));
			int downlength = cursor.getInt(cursor.getColumnIndex("downlength"));
			int filelen = cursor.getInt(cursor.getColumnIndex("filelen"));
			int loadover = cursor.getInt(cursor.getColumnIndex("loadover"));
			int isloading = cursor.getInt(cursor.getColumnIndex("isloading"));
			String fileWholePath = cursor.getString(cursor
					.getColumnIndex("fileWholePath"));
			String topDirid = cursor.getString(cursor
					.getColumnIndex("topDirid"));
			String topDiridWholePath = cursor.getString(cursor
					.getColumnIndex("topDiridWholePath"));
			entity = new FileDownloadEntity(id, downpath, downlength, filelen,loadover,
					isloading,fileWholePath,topDirid,topDiridWholePath);
			Log.d("FileDownloadService", "the entity is ===============FileDownloadService== " + entity);
		}
		cursor.close();
		db.close();
		return entity;
	}
	/**
	 * 
	 * 用于文件夹下载
	 * 获得  一个下载任务中其顶层文件夹为topDirid的所有文件
	 * @return
	 */
	public List<FileDownloadEntity> getEntityByTopDirid(String topDirid) {
		
		List<FileDownloadEntity> entitys = new ArrayList<FileDownloadEntity>();
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from filedownlog where topDirid = ?", new String[]{topDirid});
		while (cursor.moveToNext()) {
			
			int id = cursor.getInt(cursor.getColumnIndex("id"));
			String downpath = cursor.getString(cursor
					.getColumnIndex("downpath"));
			int downlength = cursor.getInt(cursor.getColumnIndex("downlength"));
			int filelen = cursor.getInt(cursor.getColumnIndex("filelen"));
			int loadover = cursor.getInt(cursor.getColumnIndex("loadover"));
			int isloading = cursor.getInt(cursor.getColumnIndex("isloading"));
			String fileWholePath = cursor.getString(cursor
					.getColumnIndex("fileWholePath"));
			String topDiridVal = cursor.getString(cursor
					.getColumnIndex("topDirid"));
			String topDiridWholePath = cursor.getString(cursor
					.getColumnIndex("topDiridWholePath"));
			entitys.add(new FileDownloadEntity(id, downpath, downlength, filelen,loadover,
					isloading,fileWholePath,topDiridVal,topDiridWholePath));
		}
		cursor.close();
		db.close();
		return entitys;
	}
	
	//add by gaoge 2011-04-21
public List<FileDownloadEntity> getEntityByTopDirRealPath(String topDirpath) {
		
		List<FileDownloadEntity> entitys = null;
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from filedownlog where topDiridWholePath = ?", new String[]{topDirpath});
		if(null != cursor && cursor.getCount() > 0){
			entitys = new ArrayList<FileDownloadEntity>();
		}
		while (cursor.moveToNext()) {
			
			int id = cursor.getInt(cursor.getColumnIndex("id"));
			String downpath = cursor.getString(cursor
					.getColumnIndex("downpath"));
			int downlength = cursor.getInt(cursor.getColumnIndex("downlength"));
			int filelen = cursor.getInt(cursor.getColumnIndex("filelen"));
			int loadover = cursor.getInt(cursor.getColumnIndex("loadover"));
			int isloading = cursor.getInt(cursor.getColumnIndex("isloading"));
			String fileWholePath = cursor.getString(cursor
					.getColumnIndex("fileWholePath"));
			String topDiridVal = cursor.getString(cursor
					.getColumnIndex("topDirid"));
			String topDiridWholePath = cursor.getString(cursor
					.getColumnIndex("topDiridWholePath"));
			entitys.add(new FileDownloadEntity(id, downpath, downlength, filelen,loadover,
					isloading,fileWholePath,topDiridVal,topDiridWholePath));
		}
		cursor.close();
		db.close();
		return entitys;
	}
	/**
	 * 获得  所有文件  并按topDirid 进行分类  封装到一个map里
	 * @return
	 */
	public Map<String,List<FileDownloadEntity>> getAllFileGroupByDir(){
		String sql = "select topDirid from filedownlog where topDirid group by topDirid";
		Map<String,List<FileDownloadEntity>> maps = new HashMap<String, List<FileDownloadEntity>>();
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(sql,null);
		while (cursor.moveToNext()) {
			String topDiridVal = cursor.getString(cursor
					.getColumnIndex("topDirid"));
			if(topDiridVal!=null){
				List<FileDownloadEntity> entitys = getEntityByTopDirid(topDiridVal);
				maps.put(topDiridVal,entitys);
			}
		}
		cursor.close();
		db.close();
		return maps;
	}
	/**
	 * 获得所有要下载文件的任务（不包括文件夹）
	 * @return
	 */
	public List<FileDownloadEntity> getFile() {
		List<FileDownloadEntity> entitys = new ArrayList<FileDownloadEntity>();
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from filedownlog where topDirid is null",null);
		while (cursor.moveToNext()) {
			int id = cursor.getInt(cursor.getColumnIndex("id"));
			String downpath = cursor.getString(cursor
					.getColumnIndex("downpath"));
			int downlength = cursor.getInt(cursor.getColumnIndex("downlength"));
			int filelen = cursor.getInt(cursor.getColumnIndex("filelen"));
			int loadover = cursor.getInt(cursor.getColumnIndex("loadover"));
			int isloading = cursor.getInt(cursor.getColumnIndex("isloading"));
			String fileWholePath = cursor.getString(cursor
					.getColumnIndex("fileWholePath"));
			String topDiridVal = cursor.getString(cursor
					.getColumnIndex("topDirid"));
			String topDiridWholePath = cursor.getString(cursor
					.getColumnIndex("topDiridWholePath"));
			entitys.add(new FileDownloadEntity(id, downpath, downlength, filelen,loadover,
					isloading,fileWholePath,topDiridVal,topDiridWholePath));
		}
		cursor.close();
		db.close();
		return entitys;
	}
	/**
	 * 获得所有要下载的任务
	 * 
	 * @return
	 */
	public List<FileDownloadEntity> getAll() {
		List<FileDownloadEntity> entitys = new ArrayList<FileDownloadEntity>();
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from filedownlog", null);
		while (cursor.moveToNext()) {
			int id = cursor.getInt(cursor.getColumnIndex("id"));
			String downpath = cursor.getString(cursor
					.getColumnIndex("downpath"));
			int downlength = cursor.getInt(cursor.getColumnIndex("downlength"));
			int filelen = cursor.getInt(cursor.getColumnIndex("filelen"));
			int loadover = cursor.getInt(cursor.getColumnIndex("loadover"));
			int isloading = cursor.getInt(cursor.getColumnIndex("isloading"));
			String fileWholePath = cursor.getString(cursor
					.getColumnIndex("fileWholePath"));
			String topDirid = cursor.getString(cursor
					.getColumnIndex("topDirid"));
			String topDiridWholePath = cursor.getString(cursor
					.getColumnIndex("topDiridWholePath"));
			entitys.add(new FileDownloadEntity(id, downpath, downlength, filelen,loadover,
					isloading,fileWholePath,topDirid,topDiridWholePath));
		}
		cursor.close();
		db.close();
		return entitys;
	}
	/**
	 * 保存一个文件id对应的下载状态
	 * 
	 * @param path
	 * @param map
	 */
	public void save(String fileid,int filelen,String fileWholePath,String topDirid,String topDiridWholePath) {// int threadid, int
		// position
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.beginTransaction();
		try {
			db
					.execSQL(
							"insert into filedownlog(downpath, downlength,filelen,loadover,isloading,fileWholePath,topDirid,topDiridWholePath) values(?,?,?,?,?,?,?,?)",
							new Object[] { fileid, 0,filelen, 0, 1,fileWholePath ,topDirid,topDiridWholePath});
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
		db.close();
	}

	/**
	 * 实时更新每条线程已经下载的文件长度
	 * 
	 * @param path
	 * @param map
	 */
	public void update(String path, int downlength) {
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.beginTransaction();
		try {
			db.execSQL("update filedownlog set downlength=? where downpath=?",
					new Object[] { downlength, path });
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
		db.close();
	}

	/**
	 * 删除一个文件对应的下载记录
	 * 
	 * @param path
	 */
	public void deleteFile(String path) {
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.execSQL("delete from filedownlog where downpath=?",
				new Object[] { path });
		db.close();
	}
	/**
	 * 删除一个文件夹对应的下载记录
	 * 
	 * @param path
	 */
	public void deleteTopDir(String topDirid) {
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.execSQL("delete from filedownlog where topDirid=?",
				new Object[] { topDirid });
		db.close();
	}
	
	/**
	 * 删除所有
	 */
	public void deleteAll(){
		String sql = "delete from filedownlog";
		SQLiteDatabase db = openHelper.getReadableDatabase();
		db.execSQL(sql);
		db.close();
	}

	//add by gaoge 2011-04-27 
	public String getParentRootPath(String filepath){
		String parentRootDir = null ;
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(
				"select topDiridWholePath from filedownlog where fileWholePath=?",
				new String[] { filepath });
		while (cursor.moveToNext()) {
			parentRootDir = cursor.getString(0);
		}
		cursor.close();
		db.close();
		return parentRootDir;
	}
}
